﻿#ifndef SERVER_USERCONNECT_H
#define SERVER_USERCONNECT_H


#include "QTcpServer"
#include "QTcpSocket"
#include "QUdpSocket"


class Server_userConnect
{
public:
    //服务器类型枚举
    enum serverType{
        TcpServer,
        UdpServer,
    };


    //用户信息
    struct usrMsg{
        QTcpSocket* socket = nullptr;
        QString usrID; //用户ID
        QString usrPsw; //用户密码,暂时废弃，不验证
    };

    //服务器信息
    struct serverMsg{
        QString usrID; //用户的ID信息
        QString proxyName = "Default"; //默认映射名称
        QTcpSocket* usrSocket = nullptr; //用户套接字
        serverType type = serverType::TcpServer; //服务器类型
        QTcpServer* tcpServer = nullptr; //TCP指针
        QUdpSocket* udpServer = nullptr; //UDP指针
        uint16_t proxyPort = 0; //映射给客户端的端口，注意：这里的端口由客户端进行解析，服务端只是记录
        bool persistent = false; //持久保持
    };


private:
    QTcpServer* server = nullptr; //服务器指针
    uint32_t maxUserNum = 0; //最大用户接入数

    QList<usrMsg> usrList; //用户列表
    QList<serverMsg> serverList; //服务列表


public:
    Server_userConnect(uint16_t port,uint32_t usrNum = 100);
    ~Server_userConnect();

    void OnTcpConnect(); //用户进入
    void OnTcpReadyRead(QTcpSocket * tSocket);//服务器TCP收到数据
    void OnTcpDisConnect(QTcpSocket * tSocket);//用户断开连接
    bool isValid(); //判断是否有效

    void addUser(QString id,QTcpSocket* socket); //添加用户信息，如果用户存在，则清理存在的信息
    bool removeUser(QString id); //移除在线用户
    QString getUserId(QTcpSocket* socket); //获取用户的文本ID

    QString getTcpAddressSign(QTcpSocket * socket); //获取TCP唯一链接标志
    QString getUdpAddressSign(QHostAddress host, quint16 port); //获取UDP唯一链接标志

    QTcpSocket* getTcpSocket(QTcpSocket* userSocket,QString AddressSign,uint16_t proxyPort); //根据AddressSign获取TCP指针
    QUdpSocket* getUdpSocket(QTcpSocket *userSocket,uint16_t proxyPort); //获取UDP服务器指针，这里不需要获取连接的Socket，因为UDP不面向连接

public:
    bool checkPort(uint16_t port); //检查端口是否被占用
    uint16_t getPort(uint16_t srcPort); //获取有效端口

    void addProxyTcpServer(QString proxyName, QString userId, QTcpSocket* userSocket, uint16_t listenPort, uint16_t proxyPort, bool persistent = false);//添加TCP监视服务
    void addProxyUdpServer(QString proxyName, QString userId, QTcpSocket* userSocket, uint16_t listenPort, uint16_t proxyPort, bool persistent = false);//添加UDP监视服务
    void removeProxy(QTcpSocket* userSocket, uint16_t proxyPort); //移除映射信息


    void removeProxyTcpUser(QTcpSocket * userSocket, QTcpSocket* connectSocket,uint16_t proxyPort); //断开映射的服务器TCP的某一个用户


public:
    void OnProxyServerTcpConnect(QTcpServer* proxyServer, QTcpSocket *userSocket, uint16_t proxyPort); //映射TCP用户进入
    void OnProxyServerTcpReadyRead(QTcpSocket * tSocket, QTcpSocket *userSocket, uint16_t proxyPort);//服务器映射TCP收到数据
    void OnProxyServerTcpDisConnect(QTcpSocket * tSocket, QTcpSocket *userSocket);//映射TCP用户断开连接

    void OnProxyServerUdpReadyRead(QUdpSocket * udpServer, QTcpSocket *userSocket, uint16_t proxyPort);//服务器映射UDP收到数据(服务套接字，客户套接字，客户远程转发端口)
};

#endif // SERVER_USERCONNECT_H
